import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_app/net_data/api.dart';
import 'package:flutter_app/util/ToastUtil.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:fluttertoast/fluttertoast.dart';

class HttpManager {
  // 工厂模式 : 单例公开访问点
  factory HttpManager() => _getInstance();

  // 静态私有成员，没有初始化
  static late HttpManager _instance;

  // 私有构造函数
  HttpManager._internal() {
    ///处理需要登录
    if (_dio == null) {
      _dio = Dio(BaseOptions(connectTimeout: 10000, baseUrl: Api.HOST));
      _dio.interceptors.add(LogInterceptor());
    }
  }

  // 静态、同步、私有访问点
  static HttpManager _getInstance() {
    if (_instance == null) {
      _instance = HttpManager._internal();
    }
    return _instance;
  }

  ///----------------------------------------------------------------------------------------------
  Dio getDio() {
    return _dio;
  }

  late Dio _dio;

  static const int CONNECT_TIMEOUT = 10000;
  static const int RECEIVE_TIMEOUT = 10000;

  getRequest(String url,
      {Map<String, dynamic> ? params,
        Function? success,
        Function ?error,
        bool toast = true,
        bool needLoading = true,
        Options ?options,
        bool skipEncrypt = false}) async {
    Response ? response;
    try {
      EasyLoading.show(status: 'loading...');
      response =
      await getDio().get(url, queryParameters: params, options: options);
      if (response != null && response.statusCode == 200) {
        var responseData = response.data;
        print("HTTP: responseData " + responseData.toString());

        if (success != null) {
          success(responseData);
        }
      } else {
        print("HTTP: responseData " +
            '${response.statusCode}' +
            '${response.statusMessage}');
        _handError(response.statusCode, response.statusMessage,
            errorCallback: error, showToast: toast);
      }
    } on DioError catch (e) {

      _handError(response?.statusCode, response?.statusMessage,
          errorCallback: error, showToast: toast);
    } catch (e) {
      debugPrint("***************异常信息***************：");
      debugPrint("异常信息:" + e.toString());
    } finally {
      EasyLoading.dismiss();
    }
  }

  // 返回错误信息
  // ignore: missing_return
  Future _handError(int ?code, String ?errorMsg,
      {Function ?errorCallback, bool showToast = true}) {
    if (showToast) {
      // Fluttertoast.showToast(msg: errorMsg ?? "接口数据出错了");
      if(errorMsg!=null){
        ToastUtil.toastShort(errorMsg);
      }else{
        ToastUtil.toastShort('接口数据出错了');
      }

    }
    if (errorCallback != null) {
      errorCallback(code, errorMsg);
    }
    return errorCallback!(code, errorMsg);
  }
}
